// 登录页面功能
function initLoginPage() {
    console.log('初始化登录页面');
    
    // 检查 Supabase 是否初始化
    if (!supabase) {
        console.error('Supabase 未初始化');
        return;
    }
    
    // 获取DOM元素
    const loginForm = document.getElementById('login-form');
    const userInfo = document.getElementById('user-info');
    const messageDiv = document.getElementById('message');
    const userEmail = document.getElementById('user-email');
    const avatar = document.getElementById('avatar');
    const logoutBtn = document.getElementById('logout-btn');
    
    // 登录方式切换
    const emailTab = document.getElementById('email-tab');
    const phoneTab = document.getElementById('phone-tab');
    const emailForm = document.getElementById('email-login-form');
    const phoneForm = document.getElementById('phone-login-form');
    
    // 邮箱登录元素
    const emailInput = document.getElementById('email');
    const passwordInput = document.getElementById('password');
    const loginBtn = document.getElementById('login-btn');
    
    // 手机登录方式切换
    const phoneCodeTab = document.getElementById('phone-code-tab');
    const phonePasswordTab = document.getElementById('phone-password-tab');
    const phoneCodeLogin = document.getElementById('phone-code-login');
    const phonePasswordLogin = document.getElementById('phone-password-login');
    
    // 手机验证码登录元素
    const phoneInput = document.getElementById('phone');
    const verificationInput = document.getElementById('verification-code');
    const sendCodeBtn = document.getElementById('send-code-btn');
    const phoneCodeLoginBtn = document.getElementById('phone-code-login-btn');
    
    // 手机密码登录元素
    const phonePasswordInput = document.getElementById('phone-password-input');
    const phoneLoginPassword = document.getElementById('phone-login-password');
    const phonePasswordLoginBtn = document.getElementById('phone-password-login-btn');
    
    // 切换登录方式
    if (emailTab && phoneTab) {
        emailTab.addEventListener('click', () => {
            emailTab.classList.add('active');
            phoneTab.classList.remove('active');
            emailForm.classList.remove('hidden');
            phoneForm.classList.add('hidden');
        });
        
        phoneTab.addEventListener('click', () => {
            phoneTab.classList.add('active');
            emailTab.classList.remove('active');
            phoneForm.classList.remove('hidden');
            emailForm.classList.add('hidden');
        });
    }
    
    // 手机登录方式切换
    if (phoneCodeTab && phonePasswordTab) {
        phoneCodeTab.addEventListener('click', () => {
            phoneCodeTab.classList.add('active');
            phonePasswordTab.classList.remove('active');
            phoneCodeLogin.classList.remove('hidden');
            phonePasswordLogin.classList.add('hidden');
        });
        
        phonePasswordTab.addEventListener('click', () => {
            phonePasswordTab.classList.add('active');
            phoneCodeTab.classList.remove('active');
            phonePasswordLogin.classList.remove('hidden');
            phoneCodeLogin.classList.add('hidden');
        });
    }
    
    // 手机号输入格式化
    if (phoneInput) {
        phoneInput.addEventListener('input', (e) => {
            const formatted = formatPhoneNumber(e.target.value);
            if (formatted !== e.target.value) {
                e.target.value = formatted;
            }
        });
    }
    
    if (phonePasswordInput) {
        phonePasswordInput.addEventListener('input', (e) => {
            const formatted = formatPhoneNumber(e.target.value);
            if (formatted !== e.target.value) {
                e.target.value = formatted;
            }
        });
    }
    
    // 发送验证码
    if (sendCodeBtn) {
        sendCodeBtn.addEventListener('click', async (e) => {
            e.preventDefault();
            
            const phone = phoneInput ? phoneInput.value.replace(/\s+/g, '') : '';
            
            if (!validatePhone(phone)) {
                showMessage(messageDiv, '请输入有效的手机号码', 'error');
                return;
            }
            
            await sendVerificationCode(phone, sendCodeBtn);
        });
    }
    
    // 邮箱登录
    if (loginBtn) {
        loginBtn.addEventListener('click', (e) => {
            e.preventDefault();
            
            const email = emailInput ? emailInput.value.trim() : '';
            const password = passwordInput ? passwordInput.value : '';
            
            if (!email || !password) {
                showMessage(messageDiv, '请输入邮箱和密码', 'error');
                return;
            }
            
            if (!validateEmail(email)) {
                showMessage(messageDiv, '请输入有效的邮箱地址', 'error');
                return;
            }
            
            loginWithEmail(email, password);
        });
    }
    
    // 手机验证码登录
    if (phoneCodeLoginBtn) {
        phoneCodeLoginBtn.addEventListener('click', (e) => {
            e.preventDefault();
            
            const phone = phoneInput ? phoneInput.value.replace(/\s+/g, '') : '';
            const code = verificationInput ? verificationInput.value : '';
            
            if (!phone || !code) {
                showMessage(messageDiv, '请输入手机号和验证码', 'error');
                return;
            }
            
            if (!validatePhone(phone)) {
                showMessage(messageDiv, '请输入有效的手机号码', 'error');
                return;
            }
            
            if (code.length !== 6) {
                showMessage(messageDiv, '请输入6位验证码', 'error');
                return;
            }
            
            loginWithPhoneCode(phone, code);
        });
    }
    
    // 手机密码登录
    if (phonePasswordLoginBtn) {
        phonePasswordLoginBtn.addEventListener('click', (e) => {
            e.preventDefault();
            
            const phone = phonePasswordInput ? phonePasswordInput.value.replace(/\s+/g, '') : '';
            const password = phoneLoginPassword ? phoneLoginPassword.value : '';
            
            if (!phone || !password) {
                showMessage(messageDiv, '请输入手机号和密码', 'error');
                return;
            }
            
            if (!validatePhone(phone)) {
                showMessage(messageDiv, '请输入有效的手机号码', 'error');
                return;
            }
            
            loginWithPhonePassword(phone, password);
        });
    }
    
    // 退出登录
    if (logoutBtn) {
        logoutBtn.addEventListener('click', async () => {
            try {
                const { error } = await supabase.auth.signOut();
                
                if (error) {
                    throw error;
                }
                
                showLoginForm();
                if (emailInput) emailInput.value = '';
                if (passwordInput) passwordInput.value = '';
                if (phoneInput) phoneInput.value = '';
                if (verificationInput) verificationInput.value = '';
                if (phonePasswordInput) phonePasswordInput.value = '';
                if (phoneLoginPassword) phoneLoginPassword.value = '';
                showMessage(messageDiv, '您已成功退出登录', 'success');
                
            } catch (error) {
                console.error('退出登录错误:', error);
                showMessage(messageDiv, '退出登录失败: ' + error.message, 'error');
            }
        });
    }
    
    // 发送验证码函数
    async function sendVerificationCode(phone, button) {
        try {
            setButtonLoading(button, true, '发送中...');
            hideMessage(messageDiv);
            
            const { data, error } = await supabase.auth.signInWithOtp({
                phone: `+86${phone}`,
                options: {
                    channel: 'sms'
                }
            });
            
            if (error) {
                throw error;
            }
            
            showMessage(messageDiv, '验证码已发送到您的手机', 'success');
            startCountdown(button);
            
        } catch (error) {
            console.error('发送验证码错误:', error);
            showMessage(messageDiv, '发送验证码失败: ' + error.message, 'error');
        } finally {
            setButtonLoading(button, false);
        }
    }
    
    // 邮箱登录函数
    async function loginWithEmail(email, password) {
        try {
            setButtonLoading(loginBtn, true);
            hideMessage(messageDiv);
            
            const { data, error } = await supabase.auth.signInWithPassword({
                email: email,
                password: password
            });
            
            if (error) {
                throw error;
            }
            
            showUserInfoCommon(data.user, userEmail, null, avatar);
            showMessage(messageDiv, '登录成功！', 'success');
            
        } catch (error) {
            console.error('邮箱登录错误:', error);
            showMessage(messageDiv, '登录失败: ' + error.message, 'error');
        } finally {
            setButtonLoading(loginBtn, false);
        }
    }
    
    // 手机验证码登录函数
    async function loginWithPhoneCode(phone, code) {
        try {
            setButtonLoading(phoneCodeLoginBtn, true);
            hideMessage(messageDiv);
            
            const { data, error } = await supabase.auth.verifyOtp({
                phone: `+86${phone}`,
                token: code,
                type: 'sms'
            });
            
            if (error) {
                throw error;
            }
            
            showUserInfoCommon(data.user, userEmail, null, avatar);
            showMessage(messageDiv, '手机验证码登录成功！', 'success');
            
        } catch (error) {
            console.error('手机验证码登录错误:', error);
            showMessage(messageDiv, '登录失败: ' + error.message, 'error');
        } finally {
            setButtonLoading(phoneCodeLoginBtn, false);
        }
    }
    
    // 手机密码登录函数
    async function loginWithPhonePassword(phone, password) {
        try {
            setButtonLoading(phonePasswordLoginBtn, true);
            hideMessage(messageDiv);
            
            // 首先尝试使用手机号作为用户名登录
            const { data, error } = await supabase.auth.signInWithPassword({
                phone: `+86${phone}`,
                password: password
            });
            
            if (error) {
                // 如果失败，尝试使用手机号作为邮箱登录
                const { data: emailData, error: emailError } = await supabase.auth.signInWithPassword({
                    email: `${phone}@phone.user`,
                    password: password
                });
                
                if (emailError) {
                    throw error;
                }
                
                showUserInfoCommon(emailData.user, userEmail, null, avatar);
                showMessage(messageDiv, '手机密码登录成功！', 'success');
                return;
            }
            
            showUserInfoCommon(data.user, userEmail, null, avatar);
            showMessage(messageDiv, '手机密码登录成功！', 'success');
            
        } catch (error) {
            console.error('手机密码登录错误:', error);
            showMessage(messageDiv, '登录失败: ' + error.message, 'error');
        } finally {
            setButtonLoading(phonePasswordLoginBtn, false);
        }
    }
    
    // 显示用户信息
    function showUserInfo(user) {
        if (loginForm) loginForm.style.display = 'none';
        if (userInfo) userInfo.style.display = 'block';
        showUserInfoCommon(user, userEmail, null, avatar);
    }
    
    // 显示登录表单
    function showLoginForm() {
        if (loginForm) loginForm.style.display = 'block';
        if (userInfo) userInfo.style.display = 'none';
    }
    
    // 检查用户是否已登录
    async function checkAuth() {
        try {
            const session = await checkAuth();
            
            if (session) {
                showUserInfo(session.user);
            } else {
                showLoginForm();
            }
        } catch (error) {
            console.error('检查认证状态错误:', error);
        }
    }
    
    // 初始化检查认证状态
    checkAuth();
    
    // 监听认证状态变化
    supabase.auth.onAuthStateChange((event, session) => {
        console.log('认证状态变化:', event, session);
        if (event === 'SIGNED_IN' && session) {
            showUserInfo(session.user);
        } else if (event === 'SIGNED_OUT') {
            showLoginForm();
        }
    });
}